<?php
/**
 * Created by PhpStorm.
 * User: lyq
 * Date: 2018/8/18
 * Time: 上午1:08
 */
namespace app\admin\controller;

use think\Exception;
use think\Db;
use think\Session;

class Admin extends Common
{
    public function index()
    {
        return $this->fetch();
    }

    //角色列表
    public function roleList()
    {
        //标题
        $this->templateTitle("角色列表");

        //获取所有用户
        $list = Db::name("admin_role")
            ->where("is_valid", 1)
            ->order("create_time DESC")
            ->paginate(10);

       // echo Db::name("admin_role")->getLastSql();
        $this->assign("list", $list);

        return $this->fetch();
    }

    //添加角色
    public function addRole()
    {
        if (request()->isGet())
        {
            $this->layoutModal();

            return $this->fetch();
        }

        //提交角色添加
        if (request()->isAjax())
        {
            //角色名称
            $name = request()->param("name");
            if (empty($name))
            {
                $this->ajaxError('请输入角色名称');
            }

            //保证角色名唯一
            $roleCount = Db::name("admin_role")
                ->where("is_valid", 1)
                ->where("name", $name)
                ->count();
            if ($roleCount)
            {
                $this->ajaxError("【" . $name . "】" . "此角色名称已存在");
            }

            //角色描述
            $desc = request()->param("desc");

            //角色权限
            $authority = request()->post("authority/a");
            if (empty($authority))
            {
                $this->ajaxError("请选择角色权限");
            }

            //角色数据
            $data = array(
                "name" => $name,
                "is_valid" => 1,
                "description" => $desc,
                "authority" => serialize($authority),
                "create_time" => now_datetime(),
                "update_time" => now_datetime(),
            );

            Db::name("admin_role")->insert($data);

            $this->ajaxSuccess('角色添加成功');
        }
    }

    //删除角色
    public function removeRole()
    {
        if (request()->isAjax())
        {
            //角色ID
            $roleId = request()->param("rid");
            //发现角色下是否有管理员
            $find = Db::name("admin_user")
                ->where("is_valid", 1)
                ->where("role_id", $roleId)
                ->find();
            if($find){
                return $this->ajaxError("此角色下有管理员，请删除后再操作");
            }else{
                //删除此角色
                Db::name("admin_role")
                    ->where("id", $roleId)
                    ->delete();
                return $this->ajaxSuccess("角色删除成功");
            }

        }
    }
    //删除管理员
    public function removeAdmin()
    {
        if (request()->isAjax())
        {
            $roleId = request()->param("rid");
            //删除管理员
            Db::name("admin_user")
                ->where("is_valid", 1)
                ->where("id", $roleId)
                ->delete();
            return $this->ajaxSuccess("管理员删除成功");
        }
    }
    //修改角色
    public function editRole()
    {
        //渲染
        if (request()->isGet())
        {
            $this->layoutModal();

            //角色ID
            $roleId = request()->param("rid");

            //获取角色信息
            $role = Db::name("admin_role")
                ->where("is_valid", 1)
                ->where("id", $roleId)
                ->find();

            //检测角色是否存在
            if (empty($role))
            {
                $this->error('此角色数据不存在');
            }

            //处理角色权限
            $role["authority"] = unserialize($role["authority"]);

            $this->assign("role", $role);

            return $this->fetch();
        }

        //处理
        if (request()->isAjax())
        {
            //角色ID
            $roleId = request()->param("rid");

            //角色名称
            $name = request()->param("name");
            if (empty($name))
            {
                return $this->ajaxError('请输入角色名称');
            }

            //保证角色名唯一
            $roleCount = Db::name("admin_role")
                ->where("is_valid", 1)
                ->where("id", "NEQ", $roleId)
                ->where("name", $name)
                ->count();
            if ($roleCount)
            {
                return $this->ajaxError("【" . $name . "】" . "此角色名称已存在");
            }

            //角色描述
            $desc = request()->param("desc");

            //角色权限
            $authority = request()->post("authority/a");
            if (empty($authority))
            {
                return $this->ajaxError('请选择角色权限');
            }

            //角色数据
            $data = array(
                "name" => $name,
                "is_valid" => 1,
                "description" => $desc,
                "authority" => serialize($authority),
                "update_time" => now_datetime(),
            );

            Db::name("admin_role")
                ->where("id", $roleId)
                ->update($data);

            return $this->ajaxSuccess('角色编辑成功');
        }
    }

    //管理员列表
    public function adminList()
    {
        //获取所有管理员
        $list = Db::name("admin_user")
            ->alias("au")
            ->join("__ADMIN_ROLE__ ar", "ar.id=au.role_id", "LEFT")
            ->where("au.is_valid", 1)
            ->order("au.create_time DESC")
            ->field("au.*,ar.name AS role_name")
            ->paginate(10);
        $this->assign("list", $list);

        return $this->fetch();
    }

    //添加管理员
    public function addAdmin()
    {
        //渲染
        if (request()->isGet())
        {
            $this->layoutModal();

            //获取角色列表
            $this->assign("role_list", $this->getAllRoles());

            return $this->fetch();
        }

        //处理
        if (request()->isAjax())
        {
            //角色
            $roleId = request()->param("role");

            //管理员名称
            $name = request()->param("name");
            $count = Db::name("admin_user")
                ->where("is_valid", 1)
                ->where("name", $name)
                ->count();
            if ($count)
            {
                $this->ajaxError("【" . $name . "】" . '管理员名称已存在');
            }

            //描述信息
            $desc = request()->param("desc");

            //管理员账号
            $username = request()->param("username");
            $count = Db::name("admin_user")
                ->where("is_valid", 1)
                ->where("username", $username)
                ->count();
            if ($count)
            {
                return $this->ajaxError("【" . $username . "】" . '管理员账号已存在');
            }

            //生成密码
            $random = rand(100000, 999999);
            $password = md5($random . request()->param("password") . $random);

            //生成数据
            $data = array(
                "role_id" => $roleId,
                "name" => $name,
                "description" => $desc,
                "username" => $username,
                "password" => $password,
                "salt" => $random,
                "is_valid" => 1,
                "is_root" => 0,
                "create_time" => now_datetime(),
                "update_time" => now_datetime(),
                "avatar" => "",
            );

            Db::name("admin_user")->insert($data);

            return $this->ajaxSuccess('添加管理员成功');
        }
    }

    // 编辑管理员
    public function editAdmin()
    {
        //管理员id
        $aid = input('aid');

        //获取管理员信息
        $admin = Db::name('admin_user')
            ->where('id', $aid)
            ->find();

        if (request()->isGet())
        {
            $this->layoutModal();

            //获取角色列表
            $this->assign("role_list", $this->getAllRoles());

            $this->assign('admin', $admin);

            return $this->fetch();
        }

        if (request()->isAjax())
        {
            //角色
            $roleId = input('role');

            //管理员名称
            $name = input('name');
            $count = Db::name('admin_user')
                ->where('is_valid', 1)
                ->where('id', 'NEQ', $aid)
                ->where('name', $name)
                ->count();
            if ($count)
            {
                $this->ajaxError('管理员【' . $name . '】已存在！');
            }

            //描述信息
            $desc = input('desc');

            //管理员账号
            $username = input('username');
            $count = Db::name('admin_user')
                ->where('is_valid', 1)
                ->where('id', 'NEQ', $aid)
                ->where('username', $username)
                ->count();
            if ($count)
            {
                return $this->ajaxError('管理员【' . $username . '】已存在！');
            }

            $data = [
                'role_id' => $roleId,
                'name' => $name,
                'description' => $desc,
                'username' => $username,
                'update_time' => now_datetime(),
            ];

            // 密码
            if(!empty(request()->param('password'))){
                $data['password'] = md5($admin['salt'] . request()->param("password") . $admin['salt']);
            }

            // 更新数据
            Db::name('admin_user')
                ->where('id', $aid)
                ->update($data);

            $this->ajaxSuccess('编辑管理员成功！');
        }
    }

    // 修改密码
    public function editPwd()
    {

        if (request()->isGet())
        {
            $this->layoutModal();

            return $this->fetch();
        }

        if (request()->isAjax())
        {   $oldpassword = trim(input('oldpassword'));
            $newpassword = trim(input('newpassword'));
            $conpassword = trim(input('conpassword'));
            if(empty($oldpassword)){
                return $this->ajaxError('请输入原登录密码');
            }
            if(empty($newpassword)){
                return $this->ajaxError('请输入新登录密码');
            }
            if($newpassword!=$conpassword){
                return $this->ajaxError('新登录密码和确认登录密码不一致');
            }
            $admin = Session::get('H_ADMIN_LOGIN_USER');
            $admin_user = Db::name('admin_user')->where('id',$admin['id'])->find();

            $md5pwd = md5($admin_user['salt'].$oldpassword.$admin_user['salt']);
            if($md5pwd!=$admin_user['password']){
                return $this->ajaxError('原密码输入错误');
            }
            $password = md5($admin_user['salt'].$newpassword.$admin_user['salt']);
            $data = [
                'password'=>$password
            ];
            $save = Db::name('admin_user')
                ->where('id',$admin['id'])
                ->update($data);
            if($save){
                $this->ajaxSuccess('密码修改成功，下次登录请使用新密码！');
            }else{
                $this->ajaxError('服务器繁忙，请稍后再试');
            }

        }
    }

    //获取所有的角色
    private function getAllRoles()
    {
        $list = Db::name("admin_role")
            ->where("is_valid", 1)
            ->field("id,name")
            ->select();

        if ($list)
        {
            return $list;
        }
        else
        {
            return array();
        }
    }
}